import './WeChartBinding.scss'
import { v4 } from 'uuid'
import { useEffect, useState } from 'react'
import { useRequest } from 'alova/client'

import { Http } from '../../API'
import { API_LIST } from '../../API/Api'
import { PutIndexedDB } from '../../Utils/IndexedDB'
import { WeChatConfig } from '../../Config/config'
const { appid, redirect_uri } = WeChatConfig
const WeChartBinding = ({ ModalEvent, Off }) => {
    const [uuid] = useState(v4())

    const { send } = useRequest(params => Http({ url: 'posWeChatBinding', params }), { immediate: false })
    const { send: getOperator } = useRequest(() => Http({ url: 'getOperator' }), { immediate: false })
    useEffect(() => {
        const state = `${uuid}@${appid}`
        const get = `${API_LIST()['sseBind']}?QRUuid=${uuid}&Type=unionid`
        const codeData = {
            self_redirect: true,
            id: 'QRcode',
            appid,
            scope: 'snsapi_login',
            response_type: 'code',
            redirect_uri: window.encodeURI(redirect_uri),
            state: state,
            style: 'black',
            href: 'https://image.ljkjkf.com/intellisiteSystem_TieKe/WebTemplate/code.css',
        }

        var eventSource = new EventSource(get)
        eventSource.onopen = () => new window.WxLogin(codeData)
        eventSource.onmessage = e => {
            const { data } = e
            if (data.length > 10) {
                send({ unionid: data }).then(() => {
                    getOperator().then(async res => {
                        await PutIndexedDB('userInfo', res.list)
                        ModalEvent.emit({ type: 'RefreshUser' })
                        Off()
                    })
                })
            }
        }
        eventSource.onerror = () => eventSource.close()
        return () => { eventSource.close() }
    }, [uuid])
    return (
        <div className='WeChartBinding'>
            <div id="QRcode" />
        </div>
    )
}

export default WeChartBinding;